#! /bin/bash

#
# Download csp data files shell
#

DATA_FILE_HOME=/app/data
OK_FILE_PREFIX=CSP

TIME_WINDOW="$1"

get_current_time() {
  echo `date "+%Y-%m-%d %H:%M:%S"`
}

# Make path of data files
if [ ! -d "$DATA_FILE_HOME/$TIME_WINDOW" ]; then
  echo "Make path: $DATA_FILE_HOME/$TIME_WINDOW"
  mkdir -p "$DATA_FILE_HOME/$TIME_WINDOW"
fi

# Starting download ok file
echo "Starting download ok file of $TIME_WINDOW at: `get_current_time`"

echo '' > ${DATA_FILE_HOME}/$TIME_WINDOW/$OK_FILE_PREFIX$TIME_WINDOW.ok

while [ ! -f "${DATA_FILE_HOME}/$TIME_WINDOW/$OK_FILE_PREFIX$TIME_WINDOW.ok" ];
  do
      echo "未取到源数据ok文件, 等待5分钟再次获取"
      sleep 300

      # Starting download ok file
      echo '' > ${DATA_FILE_HOME}/$TIME_WINDOW/$OK_FILE_PREFIX$TIME_WINDOW.ok        
done

echo "Completed download ok file of  $TIME_WINDOW at: `get_current_time`"
echo ""
echo ""
echo ""
# Read data file names from csp-data-files.cnf
DATA_FILE_NAMES=$(cat ./csp-data-files.cnf)

# Starting download data files
echo "Starting download data files of $TIME_WINDOW at: `get_current_time` " 

for filename in $DATA_FILE_NAMES
do
  file="$DATA_FILE_HOME/$TIME_WINDOW/${filename/TIME_WINDOW/${TIME_WINDOW}}.tar.gz"

  if [ ! -f "$file" ]; then
    echo "Starting download data file: $file ..."
  fi
done

echo "Completed download data files of  $TIME_WINDOW at: `get_current_time`"
echo ""
echo ""
echo ""
# Starting unzip data files
echo "Starting unzip data files at: `get_current_time`"

for filename in $DATA_FILE_NAMES 
do
  txt_file="$DATA_FILE_HOME/$TIME_WINDOW/${filename/TIME_WINDOW/${TIME_WINDOW}}.txt"
  tar_file="$DATA_FILE_HOME/$TIME_WINDOW/${filename/TIME_WINDOW/${TIME_WINDOW}}.tar.gz"

  if [ ! -f "$txt_file" ]; then
    tar -xf "$tar_file" -C "$DATA_FILE_HOME/$TIME_WINDOW"
  fi

done

echo "Completed unzip data files at: `get_current_time`"
echo ""
echo ""
echo ""
# Rename ok file
if [ -f ${DATA_FILE_HOME}/$TIME_WINDOW/$OK_FILE_PREFIX$TIME_WINDOW.ok ]; then
  mv -f ${DATA_FILE_HOME}/$TIME_WINDOW/$OK_FILE_PREFIX$TIME_WINDOW.ok ${DATA_FILE_HOME}/$TIME_WINDOW/$OK_FILE_PREFIX.ok
fi

